package com.ruoyi.common.core.page;

import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.StringPath;
import com.ruoyi.common.utils.StringUtils;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.domain.Sort;

import java.util.Optional;

/**
 * 分页数据
 *
 * @author ruoyi
 */
@SuppressWarnings("rawtypes")
@Data
@Accessors(chain = true)
public class PageDomain {
	/**
	 * 当前记录起始索引
	 */
	private Integer pageNum;

	/**
	 * 每页显示记录数
	 */
	private Integer pageSize;

	/**
	 * 排序列
	 */
	private String orderByColumn;

	/**
	 * 排序的方向desc或者asc
	 */
	private String isAsc = "asc";

	/**
	 * 分页参数合理化
	 */
	private Boolean reasonable = true;

	private OrderSpecifier defaultOrder;

	public String getOrderBy() {
		if (StringUtils.isEmpty(orderByColumn)) {
			return "";
		}
		return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
	}

	public int offset() {
		return (this.pageNum - 1) * this.pageSize;
	}

	public Optional<Sort> getJpaOrderBy() {
		if (StringUtils.isEmpty(orderByColumn)) {
			return Optional.empty();
		}
		Sort sort = Sort.by(orderByColumn);
		if (isAsc.equals("asc")) {
			sort.ascending();
		} else {
			sort.descending();
		}
		return Optional.of(sort);
	}

	public Optional<OrderSpecifier> getDslOrderBy() {
		if (StringUtils.isEmpty(orderByColumn)) {
			return Optional.empty();
		}
		StringPath stringPath = Expressions.stringPath(orderByColumn);
		OrderSpecifier orderSpecifier = null;
		if (isAsc.equals("desc")) {
			orderSpecifier = stringPath.desc();
		} else {
			orderSpecifier = stringPath.asc();
		}
		return Optional.of(orderSpecifier);
	}

	public Optional<OrderSpecifier> getDefaultOrder() {
		return Optional.ofNullable(defaultOrder);
	}

	public void setIsAsc(String isAsc) {
		if (StringUtils.isNotEmpty(isAsc)) {
			// 兼容前端排序类型
			if ("ascending".equals(isAsc)) {
				isAsc = "asc";
			} else if ("descending".equals(isAsc)) {
				isAsc = "desc";
			}
			this.isAsc = isAsc;
		}
	}

	public Boolean getReasonable() {
		if (StringUtils.isNull(reasonable)) {
			return Boolean.TRUE;
		}
		return reasonable;
	}
}
